"""
    Controller for payment records.
"""

from datetime import date
import turbogears
from turbogears import widgets
from mnemoply import model
from mnemoply.mass_actions import MassAction, MassActionForm
from mnemoply.widgets import DecimalValidator, EmptyValidator, DictionaryField
from mnemoply.controllers.lookup import LookupController, TableCol, TableLookupDataSource
from mnemoply.controllers.crud import CRUDController

class MAConvertTPRtoPR(MassAction):
    target_class = model.PaymentRecord
    name = "ConvertTPRtoPR"
    title = _("Convert temporary payment record to payment record")
    display_on_lookup = False

    def __init__(self, *k, **kw):
        super(MassAction, self).__init__(*k, **kw)

    def inject_object(self, obj):
        MassAction.inject_object(self, obj)

        def get_records():
            if self.obj is None:
                return []
            else:
                return [t for t in model.TemporaryPaymentRecord.selectBy(student=obj) if t.payment == 0]

        self.form = MassActionForm(
            name=self.name,
            fields=[
                DictionaryField(
                    name="tpr_id",
                    model_object_name='TemporaryPaymentRecord',
                    not_empty=True,
                    records=get_records(),
                    label=_("Temporary payment record")
                ),
                widgets.TextField(name="amount", validator=DecimalValidator(not_empty=True), label=_("Amount")),
            ]
        )

    def call(self, payment_records, tpr_id, amount):
        amount = int(amount)
        tpr = model.TemporaryPaymentRecord.get(int(tpr_id))
        total_sum = sum([p.amount for p in payment_records])

        if amount >= 0 and total_sum >= amount and len(payment_records):
            p = payment_records[0]
            model.PaymentRecord(
                student=p.student,
                studentAgreement=p.studentAgreement,
                register=p.register,
                date=date.today(),
                amount=-amount,
                checkNumber=p.checkNumber,
                passportNumber=p.passportNumber,
                owner=p.owner,
            )
            tpr.payment = amount
            tpr.register = p.register
            self.flash_message = None
        else:
            self.flash_message = _("Payments less than entered amount.")

class MAMoveToAnotherAgreement(MassAction):
    target_class = model.PaymentRecord
    name = "move_to_another_agreement"
    title = _("Move payment record to another agreement")
    display_on_lookup = False

    def __init__(self, *k, **kw):
        super(MassAction, self).__init__(*k, **kw)

    def inject_object(self, obj):
        MassAction.inject_object(self, obj)

        def get_records():
            if self.obj is None:
                return []
            else:
                return [t for t in model.StudentAgreement.selectBy(student=obj)]

        self.form = MassActionForm(
            name=self.name,
            fields=[
                DictionaryField(
                    name="agr_id",
                    model_object_name='StudentAgreement',
                    not_empty=True,
                    records=get_records(),
                    label=_("Student Agreement")
                ),
                widgets.TextField(name="amount", validator=DecimalValidator(not_empty=True), label=_("Amount")),
            ]
        )

    def call(self, payment_records, agr_id, amount):
        amount = int(amount)
        agr = model.StudentAgreement.get(int(agr_id))
        total_sum = sum([p.amount for p in payment_records])
        if amount >= 0 and total_sum >= amount and len(payment_records):
            p = payment_records[0]

            model.PaymentRecord(
                student=p.student,
                studentAgreement=p.studentAgreement,
                register=p.register,
                date=date.today(),
                amount=-amount,
                checkNumber=p.checkNumber,
                passportNumber=p.passportNumber,
                owner=p.owner,
            )

            model.PaymentRecord(
                student=p.student,
                studentAgreement=agr,
                register=p.register,
                date=p.date,
                amount=amount,
                checkNumber=p.checkNumber,
                passportNumber=p.passportNumber,
                owner=p.owner,
            )
            self.flash_message = None
        else:
            self.flash_message = _("Payments less than entered amount.")

class MSTakingCashBack(MassAction):
    target_class = model.PaymentRecord
    name = "taking_cash_back"
    title = _("Taking cash back")
    form = MassActionForm(
        name=name,
        fields=[
            widgets.TextField(name="amount", validator=DecimalValidator(not_empty=True), label=_("Amount")),
            widgets.TextField(name="passport_number", validator=EmptyValidator(not_empty=True), label=_("Passport number")),
            widgets.TextField(name="check_number", validator=EmptyValidator(not_empty=False), label=_("Check number")),
        ]
    )

    def call(self, payment_records, amount, check_number, passport_number):
        def is_same_agreement(records):
            return len(set(r.studentAgreement for r in records)) == 1

        if not is_same_agreement(payment_records):
            self.flash_message = _("Agreements are not the same.")
            return

        if sum(p.amount for p in payment_records) < amount:
            self.flash_message = _("Sum less than amount.")
            return

        # default
        self.flash_message = None

        p = payment_records[0]
        model.PaymentRecord(
            student=p.student,
            studentAgreement=p.studentAgreement,
            register=p.register,
            date=date.today(),
            amount=-amount,
            checkNumber=check_number,
            passportNumber=passport_number,
            owner=turbogears.identity.current.user.person,
        )

class PaymentRecordController(LookupController, CRUDController):
    model_object = model.PaymentRecord
    lookup_columns = [
        TableCol(name='date', caption=_('Date'), size=5),
        TableCol(name='student', caption=_('Student')),
        TableCol(name='amount', caption=_('Amount'), size=4),
        TableCol(name='register_str', caption=_('Cash register'), size=5),
        TableCol(name='comment', caption=_('Comment'), hidden=True),
        TableCol(name='coupon', caption=_('Coupon'), hidden=True),
    ]

    edit_fields = [
        'date',
        'studentID',
        'studentAgreementID',
        'amount',
        'registerID',
    ]

    view_fields = edit_fields + [
        'passportNumber',
        'checkNumber',
        'dateOfChanges',
        'previousPaymentID',
        'comment',
        'couponID',
    ]

    def __init__(self):
        LookupController.__init__(self,
            data_source=TableLookupDataSource("payment_record_lookup"),
            columns=self.lookup_columns,
            title=self.model_object.model_title,
            default_order_asc=False,
            mass_actions_class=self.model_object,
        )
        CRUDController.__init__(self, model_object=self.model_object)

    def fill_lookup_data_defaults(self, data):
        is_parent_filled = LookupController.fill_lookup_data_defaults(self, data)
        if not is_parent_filled:
            office = turbogears.identity.current.user.office.name
            args = {'flt_register_str': office,
                    'column': ['date', 'student', 'amount', 'register_str']}
            data.update(args)

exposed = PaymentRecordController()
